package org.example;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import java.io.IOException;

public class Main {
  static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
  public static final String API_KEY = "IniJsCw0e4Cezo8jhPCtBnW8";
  public static final String SECRET_KEY = "hEhztEk9wN0XjlGr4Qvpa2bwZGHTqh5G";

  public static void main(String[] args) throws IOException {
    MediaType mediaType = MediaType.parse("application/json");
    RequestBody body = RequestBody.create(mediaType, "{\n" +
      "    \"text\": \"上海市浦东新区纳贤路701号百度上海研发中心 F4A000 张三\"\n" +
      "}");
    Request request = new Request.Builder()
      .url("https://aip.baidubce.com/rpc/2.0/nlp/v1/address?access_token=" + getAccessToken())
      .method("POST", body)
      .addHeader("Content-Type", "application/json")
      .addHeader("Accept", "application/json")
      .build();
    Response response = HTTP_CLIENT.newCall(request).execute();
    System.out.println(response.body().string());
  }

  /**
   * 从用户的AK，SK生成鉴权签名（Access Token）
   *
   * @return 鉴权签名（Access Token）
   * @throws IOException IO异常
   */
  static String getAccessToken() throws IOException {
    MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
    RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
      + "&client_secret=" + SECRET_KEY);
    Request request = new Request.Builder()
      .url("https://aip.baidubce.com/oauth/2.0/token")
      .method("POST", body)
      .addHeader("Content-Type", "application/x-www-form-urlencoded")
      .build();
    Response response = HTTP_CLIENT.newCall(request).execute();
    String accessToken = JSONObject.parseObject(response.body().string()).getString("access_token");
    return accessToken;
 //   return new JSONObject(response.body().string()).getString("access_token");
  }
}
